<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 标签编辑组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Metas_Tag_Edit extends Widget_Abstract_Metas implements Widget_Interface_Do
{
    /**
     * 入口函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
		$this->parameter->setDefault('pageSize=20');
        /** 编辑以上权限 */
        $this->user->pass('editor');
		
        /** 更新模式 */
        if (!empty($this->request->mid) && 'delete' != $this->request->do ) {
            $this->select()
			    ->where('type = ?', 'tag')
                ->where('mid = ?', $this->request->filter('int')->mid)
			    ->limit(1)
			    ->fetchRow(array($this, 'push'));

            if (!$this->have()) {
                throw new Widget_Exception(_t('标签不存在'), 404);
            }
        }
		
    }
	
    /**
     * 判断标签是否存在
     *
     * @access public
     * @param integer $mid 标签主键
     * @return boolean
     */
    public function tagExists($mid)
    {
        $tag = $this->db->select(1)
		    ->from('table.metas')
            ->where('type = ?', 'tag')
            ->where('mid = ?', $mid)
		    ->limit(1)
		    ->fetchRow();

        return $tag ? true : false;
    }

    /**
     * 判断标签名称是否存在
     *
     * @access public
     * @param string $name 标签名称
     * @return boolean
     */
    public function nameExists($name)
    {
        $select = $this->db->select('mid')
		    ->from('table.metas')
		    ->where('type = ?', 'tag')
            ->where('name = ?', $name)
            ->limit(1)
			->fetchRow();
		
        // $select->where('mid <> ?', $this->request->filter('int')->mid);		
        if ($select && $this->request->mid == $select['mid']) {
			$select = false;
        }
        return $select ? false : true;
    }

    /**
     * 生成表单
     *
     * @access public
     * @param string $action 表单动作
     * @return Form
     */
    public function form()
    {
        /** 构建表格 */
        $form = new Form($this->security->actionUrl('metas-tag-edit', false));

        /** 标签名称 */
        $name = new Form_Text('name', NULL, NULL,
        _t('标签名称 *'), _t('这是标签在站点中显示的名称.可以使用中文,如 "地球".'));
        $form->addInput($name);

        /** 标签缩略名 */
        $alias = new Form_Text('alias', NULL, NULL,
        _t('标签缩略名'), _t('标签缩略名用于创建友好的链接形式, 如果留空则默认使用标签名称.'));
        $form->addInput($alias);

        /** 标签动作 */
        $do = new Form_Hidden('do');
        $form->set($do);

        /** 标签主键 */
        $mid = new Form_Hidden('mid');
        $form->set($mid);

        /** 提交按钮 */
        $submit = new Form_Submit();
        $form->set($submit);

        if ($this->mid) {
            $name->value($this->name);
            $alias->value($this->alias);
            $do->value('update');
            $mid->value($this->mid);
            $submit->value(_t('编辑标签'));
        } else {
            $do->value('insert');
            $submit->value(_t('增加标签'));
        }

        /** 给表单增加规则 */
        $name->addRule('required', _t('必须填写标签名称'));
        $name->addRule(array($this, 'nameExists'), _t('标签名称已经存在'));
        $name->addRule('xssCheck', _t('请不要标签名称中使用特殊字符'));
        $alias->addRule('xssCheck', _t('请不要在缩略名中使用特殊字符'));

       if ($this->mid) {
            $mid->addRule('required', _t('标签主键不存在'));
            $mid->addRule(array($this, 'tagExists'), _t('标签不存在'));
        }
		
		/** 插件接口 */
		//HOOK PLUG_Tag_Form($form, $this);	
		
        return $form;
    }

    /**
     * 获取页面偏移的URL Query
     *
     * @access protected
     * @param integer $created 创建时间
     * @param string $status 状态
     * @return string
     */
    protected function getPageOffsetQuery($mid)
    {
        return 'page=' . $this->getPageOffset('mid', $mid, 'tag', $this->parameter->pageSize);
    }
	
    /**
     * 插入标签
     *
     * @access public
     * @return void
     */
    public function insertTag($values = array())
    {
		/** 插件接口 */
		//HOOK $values | PLUG_Tag_Insert($values, $this);

        /** 插入数据 */
        $insertId = $this->insert($values);
		
		/** 压入数据 */
		$this->select()
            ->where('mid = ?', $insertId)
            ->where('type = ?', 'tag')
			->limit(1)
			->fetchRow(array($this, 'push'));

		/** 插件接口 */	
		//HOOK PLUG_Tag_Insert_Success($this);
		
		return $insertId;
    }

    /**
     * 更新标签
     *
     * @access public
     * @return void
     */
    public function updateTag($values = array())
    {
		if (!$this->have()) {
		    return ;
		}

		/** 标签下所有的内容都查找出来，此处数据量大可能会超时，所以不要更新内容特别多的标签 */
		if ($this->contentsNum > 10000) {
		    throw new Widget_Exception(_t('标签内容数据量太大'), 403);
		}
		
		/** 插件接口 */
		//HOOK $values | PLUG_Tag_Update($values, $this);
		
		$mid = $this->mid;

        /** 更新数据 */
        $updateRows = $this->update($mid, $values);
		
		/** 压入数据 */
        $this->select()
            ->where('mid = ?', $mid)
            ->limit(1)
		    ->fetchRow(array($this,'push'));
		
		/** 查找所有cid, 逐个更新, 如果内容数太大, 会更新失败 */
	    $cidlist = $this->db->select()
		    ->from('table.relate')
		    ->where('mid = ?', $mid)
		    ->limit(10000)
		    ->fetchAll();
        foreach ($cidlist as $value) 
		{
			$content = $this->db->select('tagsJson')
			    ->from('table.contents')
				->where('cid = ?', $value['cid'])
				->fetchRow();
			if ($content && $content['tagsJson']) {
				$tagsJson = Json::decode($content['tagsJson']);
				if (isset($tagsJson[$mid])) {
					$tagsJson[$mid]['name'] = $this->name;
					$tagsJson[$mid]['alias'] = $this->alias;
					$this->db->update('table.contents')
					    ->where('cid = ?', $value['cid'])
					    ->values(array('tagsJson'=>Json::encode($tagsJson)))
					    ->affectedRows();
                }
            }
	    }
		
		/** 插件接口 */
		//HOOK PLUG_Tag_Update_Success($this);
		
		return $updateRows;
    }

    /**
     * 删除标签
     *
     * @access public
     * @return void
     */
    public function deleteTag($mid)
    {
		$deleteRows = false;
		$tag = $this->select()
            ->where('mid = ?', $mid)
            ->where('type = ?', 'tag')
		    ->limit(1)
		    ->fetchRow(array($this, 'push'));
		
        if (!$tag) {
			return ;
		}	

		/** 此处数据量大可能会超时 */
		if ($this->contentsNum > 10000) {
		    throw new Widget_Exception(_t('标签内容数据量太大'), 403);
		}
		
        $cidlist = $this->db->select('cid')
		    ->from('table.relate')
			->where('mid = ?', $mid)
		    ->limit(10000)
			->fetchAll();

        foreach ($cidlist as $value) 
		{
			$content = $this->db->select('tagsJson')
			    ->from('table.contents')
				->where('cid = ?', $value['cid'])
				->fetchRow();
			if ($content && $content['tagsJson']) {
				$tagsJson = Json::decode($content['tagsJson']);
				if (isset($tagsJson[$mid])) {
					
					unset($tagsJson[$mid]);

					$this->db->update('table.contents')
					    ->where('cid = ?', $value['cid'])
					    ->values(array('tagsJson'=>Json::encode($tagsJson)))
					    ->affectedRows();
				}
			}
			/** 更新内容数 */
			$this->db->delete('table.relate')
				->where('mid = ? AND cid = ?', $mid, $value['cid'])
				->affectedRows();
		}


        /** 插件接口 */
        //HOOK PLUG_Tag_Delete($this);
			
        $deleteRows = $this->delete($mid);

        /** 插件接口 */
        //HOOK PLUG_Tag_Delete_Success($this);

		return $deleteRows;
    }

    /**
     * 获取菜单标题
     *
     * @access public
     * @return string
     */
    public function getMenuTitle()
    {
        if (isset($this->request->mid)) {
            if (!empty($this->name)) {
                return _t('编辑标签: %s', $this->name);
            }
        } else {
            return _t('增加标签');
        }

        throw new Widget_Exception(_t('标签不存在'), 404);
    }
	
    public function operate()
    {
		$buttons = array();

		$buttons[] = Helper::element('a', _t('全选'), array(
		    'data-selectall'=>NULL,		
			'href'=>'javascript:void(0);'
			)
		);

		$buttons[] = Helper::element('a', _t('删除'), array(
		    'href'=>'javascript:void(0);',
		    'data-action'=>$this->security->actionUrl('metas-tag-edit?do=delete', false),
			'data-confirm'=>_t('删除不可恢复，确定删除？'),
			'data-item'=>'mid',
			'style'=>'color:red'
			)
		);

		/** 插件接口 */
		//HOOK $buttons[] | PLUG_Tag_Operate($this);
		
		return $this->widget('Widget_Operate')->render($buttons);
    }
	
    /**
     * 入口函数,绑定事件
     *
     * @access public
     * @return void
     */
    public function action()
    {
        $this->security->protect();
		
        switch ($this->request->do) {
            case 'insert':
			
				$form = $this->form();
			
		        /** 验证格式 */
                if ($message = $form->validate()) {
                    $this->result->set(key($message), current($message));
                }
				
				/** 取出数据 */
                $tag = $this->request->from(array_keys($form->getInputs()));
				$tag['type'] = 'tag';
				
		        $this->insertTag($tag);
			
                /** 提示信息 */
                $this->result->set(0, _t('标签 %s 增加成功', $this->name), array('location'=>$this->options->ucenterUrl('tags', false), 'mid'=>$this->mid));
				
            break;
            case 'update':
			
				$form = $this->form();
			
		        /** 验证格式 */
                if ($message = $form->validate()) {
                    $this->result->set(key($message), current($message));
                }
				
				/** 取出数据 */
                $tag = $this->request->from(array_keys($form->getInputs()));
				$tag['type'] = 'tag';
				
		        $this->updateTag($tag);
			
                /** 提示信息 */
                $this->result->set(0, _t('标签 %s 更新成功', $this->name), array('location'=>$this->options->ucenterUrl('tags?' . $this->getPageOffsetQuery($this->request->mid), false), 'mid'=>$this->mid));
				
            break;

            case 'delete':
			
                $mids = $this->request->filter('int')->getArray('mid');
                $deleteRows = array();

                foreach ($mids as $mid) {
		            if($this->deleteTag($mid)){ 
					    $deleteRows[] = $mid;
					}
                }
			
                /** 设置提示信息 */
                $this->result->set(
				    $deleteRows ? 0 : 1, 
				    $deleteRows ? _t('成功删除 %s 个标签', count($deleteRows)) : _t('没有标签被删除'),
				    $deleteRows
				);
				
            break;
        }

        $this->result->set(404, _t('请求的资源不存在'));
    }
}
